using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using RAG.Domain.Services;

namespace RAG.Infrastructure.Services;

/// <summary>
/// 本地文件存储实现 - 基础设施层
/// </summary>
public class LocalFileStorage : IFileStorage
{
    private readonly string _uploadPath;
    private readonly string _staticFileUrl;
    private readonly ILogger<LocalFileStorage> _logger;

    public LocalFileStorage(IConfiguration configuration, ILogger<LocalFileStorage> logger)
    {
        _uploadPath = configuration["FileStorage:UploadPath"] ?? "uploads";
        _staticFileUrl = configuration["FileStorage:StaticFileUrl"] ?? "/files";
        _logger = logger;

        // 确保上传目录存在
        Directory.CreateDirectory(_uploadPath);
    }

    public async Task<string> SaveAsync(RAG.Domain.Services.FileInfo file)
    {
        try
        {
            // 生成日期目录 (yyyyMM格式)
            var dateFolder = DateTime.Now.ToString("yyyyMM");
            var datePath = Path.Combine(_uploadPath, dateFolder);

            // 确保日期目录存在
            Directory.CreateDirectory(datePath);

            // 生成唯一文件名
            var fileName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
            var filePath = Path.Combine(datePath, fileName);

            // 保存文件
            await System.IO.File.WriteAllBytesAsync(filePath, file.Content);

            // 返回可访问的URL：/files/{yyyyMM}/{guid}_{文件名}
            var fileUrl = $"{_staticFileUrl}/{dateFolder}/{fileName}";

            _logger.LogInformation("文件保存成功: {FilePath}, URL: {FileUrl}", filePath, fileUrl);
            return fileUrl;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件保存失败: {FileName}", file.FileName);
            throw;
        }
    }

    public async Task<bool> DeleteAsync(string fileUrl)
    {
        try
        {
            // 从URL中提取文件路径
            var fileName = Path.GetFileName(fileUrl);
            var filePath = Path.Combine(_uploadPath, fileName);

            if (File.Exists(filePath))
            {
                await Task.Run(() => File.Delete(filePath));
                _logger.LogInformation("文件删除成功: {FilePath}", filePath);
                return true;
            }
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文件删除失败: {FileUrl}", fileUrl);
            return false;
        }
    }

    public Task<bool> ExistsAsync(string fileUrl)
    {
        try
        {
            var fileName = Path.GetFileName(fileUrl);
            var filePath = Path.Combine(_uploadPath, fileName);
            return Task.FromResult(File.Exists(filePath));
        }
        catch
        {
            return Task.FromResult(false);
        }
    }

    /// <summary>
    /// 获取文件的完整URL
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <returns>完整的文件URL</returns>
    public string GetFileUrl(string fileName)
    {
        return $"{_staticFileUrl}/{fileName}";
    }

    /// <summary>
    /// 从URL中获取文件路径
    /// </summary>
    /// <param name="fileUrl">文件URL</param>
    /// <returns>文件物理路径</returns>
    public string GetFilePath(string fileUrl)
    {
        var fileName = Path.GetFileName(fileUrl);
        return Path.Combine(_uploadPath, fileName);
    }
}